package com.evan.review.architecture.mvvm.model;

import android.content.Context;
import android.os.AsyncTask;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

/**
 * 笔记数据库
 * MVVM架构中的Model层的一部分
 * 使用Room数据库框架
 */
@Database(entities = {Note.class}, version = 1, exportSchema = false)
public abstract class NoteDatabase extends RoomDatabase {
    
    private static NoteDatabase instance;
    
    // 抽象方法返回DAO
    public abstract NoteDao noteDao();
    
    // 单例模式获取数据库实例
    public static synchronized NoteDatabase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(
                    context.getApplicationContext(),
                    NoteDatabase.class,
                    "note_database")
                    .fallbackToDestructiveMigration()
                    .addCallback(roomCallback)
                    .build();
        }
        return instance;
    }
    
    // 数据库创建回调，用于添加示例数据
    private static final RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            // 在数据库创建时添加一些示例数据
            new PopulateDbAsyncTask(instance).execute();
        }
    };
    
    // 异步任务，用于填充数据库示例数据
    private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
        private final NoteDao noteDao;
        
        private PopulateDbAsyncTask(NoteDatabase db) {
            noteDao = db.noteDao();
        }
        
        @Override
        protected Void doInBackground(Void... voids) {
            // 添加示例笔记
            noteDao.insert(new Note("欢迎使用笔记应用", "这是一个使用MVVM架构模式开发的笔记应用示例", "教程", 5));
            noteDao.insert(new Note("MVVM架构", "Model-View-ViewModel架构模式将应用分为三层", "架构", 4));
            noteDao.insert(new Note("LiveData", "LiveData是一个可观察的数据持有者类", "Android", 3));
            noteDao.insert(new Note("ViewModel", "ViewModel类负责为UI准备和管理数据", "Android", 4));
            noteDao.insert(new Note("Room", "Room是一个持久性库，提供了SQLite的抽象层", "Android", 3));
            return null;
        }
    }
} 